﻿using SSC.Models;
using SSC.Services;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace SSC.ViewModels
{
    public class MaintenanceViewModel : INotifyPropertyChanged
    {
        private readonly MaintenanceService _maintenanceService;

        public MaintenanceViewModel()
        {
            _maintenanceService = new MaintenanceService();
            _items = new ObservableCollection<MaintenanceItemModel>();
            LoadItems();
        }

        private ObservableCollection<MaintenanceItemModel> _items;
        public ObservableCollection<MaintenanceItemModel> Items
        {
            get => _items;
            set
            {
                _items = value;
                OnPropertyChanged();
            }
        }

        private MaintenanceItemModel _selectedItem;
        public MaintenanceItemModel SelectedItem
        {
            get => _selectedItem;
            set
            {
                _selectedItem = value;
                OnPropertyChanged();
            }
        }

        public void LoadItems()
        {
            var all = _maintenanceService.GetAllItems();
            Items.Clear();  
            foreach (var item in all)
            {
                Items.Add(item);
            }
        }

        public void AddItem(MaintenanceItemModel newItem)
        {
            _maintenanceService.AddItem(newItem);
            LoadItems();
        }

        public void DeleteItem(MaintenanceItemModel item)
        {
            if (item == null) return;
            _maintenanceService.DeleteItem(item.Id);
            LoadItems();
        }
        public void UpdateItem(MaintenanceItemModel updatedItem)
        {
            _maintenanceService.UpdateItem(updatedItem);
            LoadItems(); // 或更新集合中对应项
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
